
package de.justphil.tcg.tcgandroidclient.gui;

import de.justphil.tcg.tcgandroidclient.Example;
import de.justphil.tcg.tcgandroidclient.R;
import de.justphil.tcg.tcgandroidclient.Storage;
import de.justphil.tcg.tcgandroidclient.content.rest.RESTCreateGameResponse;
import de.justphil.tcg.tcgandroidclient.content.rest.RESTGameReadyResponse;
import de.justphil.tcg.tcgandroidclient.network.rest.RESTMessengerService;
import de.justphil.tcg.tcgandroidclient.util.StringTools;
import de.justphil.tcg.tcgandroidclient.util.TCGLog;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class LoginAct extends Activity {
	
	private Button loginButton;
	private Button registerButton;
	private CheckBox rememberCheckBox;
	private EditText userEditText;
	private EditText pwdEditText;
	private EditText restServerEditText;
	private ProgressDialog createDialog;
	private Messenger restMessenger;
	private Messenger messenger;
	private boolean bound;
	/**
	 * Class for interacting with the main interface of the service.
	 */
	private ServiceConnection connection = new ServiceConnection() {
		
		public void onServiceConnected(ComponentName className, IBinder binder) {
		
			restMessenger = ((RESTMessengerService.RESTBinder) binder).getMessenger(messenger);
			bound = true;
		}
		
		public void onServiceDisconnected(ComponentName className) {
		
			restMessenger = null;
			bound = false;
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		String restServer = getString(R.string.rest_server_url);
		Storage.setRestServer(restServer);
		Storage.setUserName(Example.USER);
		Storage.setPwd(Example.PWD);
		initializeComponents();
		messenger = new Messenger(new Handler() {
			
			@Override
			public void handleMessage(Message msg) {
			
				LoginAct.this.handleMessage(msg);
			}
		});
	}
	
	@Override
	protected void onStart() {
	
		super.onStart();
		// Bind to the service
		if (!bindService(new Intent(this, RESTMessengerService.class), connection,
				Context.BIND_AUTO_CREATE)) {
			throw new IllegalStateException("Thread binding failed!");
		}
		userEditText.setText(Storage.getUserName());
		pwdEditText.setText(Storage.getPwd());
		restServerEditText.setText(Storage.getRestServer());
	}
	
	@Override
	protected void onStop() {
	
		super.onStop();
		// Unbind from the service
		if (bound) {
			unbindService(connection);
			bound = false;
		}
	}
	
	private void handleMessage(Message msg) {
	
		switch (msg.what) {
			case RESTMessengerService.MSG_LOGGED_IN:
				handleLoggedInMsg((Long) msg.obj);
				break;
			case RESTMessengerService.MSG_ERROR:
				handleErrorMsg(msg.arg1, (String) msg.obj);
				break;
			case RESTMessengerService.MSG_NOT_RESPONDING:
				handleNotRespondingMsg();
				break;
			default:
				throw new IllegalArgumentException("Message type " + msg.what + " is unknown!");
		}
	}
	
	private void handleLoggedInMsg(Long playerId) {
	
		Storage.setPlayerId(playerId);
		ProgressDialog d = getDialog();
		if (d.isShowing()) {
			d.dismiss();
		}
		Intent intent = new Intent(LoginAct.this, HomeAct.class);
		startActivity(intent);
	}
	
	private void handleNotRespondingMsg() {
	
		ProgressDialog d = getDialog();
		if (d.isShowing()) {
			d.dismiss();
		}
		Toast.makeText(this, "The REST server is not responding!", Toast.LENGTH_LONG).show();
	}
	
	private void handleErrorMsg(int code, String message) {
	
		getDialog().dismiss();
		String text = StringTools.getString(new Object[] {
				code, ": ", message });
		Toast.makeText(this, text, Toast.LENGTH_LONG).show();
		TCGLog.w(new Object[] {
			text });
	}
	
	private void initializeComponents() {
	
		loginButton = (Button) findViewById(R.id.login_button_login);
		registerButton = (Button) findViewById(R.id.login_button_register);
		rememberCheckBox = (CheckBox) findViewById(R.id.login_checkBox_remember);
		userEditText = (EditText) findViewById(R.id.login_editText_user);
		pwdEditText = (EditText) findViewById(R.id.login_editText_pwd);
		restServerEditText = (EditText) findViewById(R.id.login_rest_server);
		loginButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			
				Storage.setUserName(userEditText.getText().toString());
				Storage.setPwd(pwdEditText.getText().toString());
				Storage.setRestServer(restServerEditText.getText().toString());
				ProgressDialog d = getDialog();
				d.setMessage("Loging in...");
				d.show();
				Message msg = Message.obtain(null, RESTMessengerService.MSG_LOG_IN);
				try {
					restMessenger.send(msg);
				}
				catch (RemoteException e) {
					throw new RuntimeException("Message could not be send!");
				}
			}
		});
		registerButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			
				// startActivity(new Intent(LoginAct.this, HomeAct.class));
			}
		});
	}
	
	private ProgressDialog getDialog() {
	
		if (createDialog == null) {
			createDialog = new ProgressDialog(this);
		}
		return createDialog;
	}
}
